import { Card,Breadcrumb, Form,Modal , Radio, Select, DatePicker ,Button,Table, Tag, Space, Pagination, message } from "antd"
import { FormOutlined ,RestOutlined } from '@ant-design/icons';
import { Link, useNavigate } from "react-router-dom"
import './index.scss'
import { useChannel } from "@/hooks/useChannel";
import { getArticleListAPI, deleteArticleAPI } from "@/apis/article";
import { useEffect, useState } from "react";

const { Option } = Select;
const { RangePicker } = DatePicker;
const Article  = () => {
    const navigate = useNavigate()
    // 获取频道列表数据
    const channelList = useChannel()
    // 收集接口所需要的字段
    const [reqData, setReqData] = useState({
        status:'',
        channel_id: '',
        begin_pubdate: '',
        end_pubdate: '',
        page: 1,
        per_page: 6
    })
    // 获取文章列表逻辑
    const [ articleList, setArticleList ] = useState()
    const [ loading, setLoading ] = useState(true) //添加loading效果
    const [ totalCount , setTotalCount ] = useState(0) //文章列表总条数

    useEffect(() =>{
      const getArticleList = async() => {
        setLoading(true) //渲染页面开启loading
        const res = await getArticleListAPI(reqData) 
        setArticleList(res.data.results) //将所需要的文章数据存进去
        setLoading(false) //页面渲染完成之后关闭loading
        setTotalCount(res.data.total_count)
      }
     getArticleList()
    } , [reqData])   
    const onFinish = (formValue) => {
       setReqData({
         ...reqData,
         channel_id: formValue.channel_id,
         status: formValue.status,
         begin_pubdate: formValue.date ? formValue.date[0].format('YYYY-MM-DD') : '',
         end_pubdate: formValue.date ? formValue.date[1].format('YYYY-MM-DD') : ''
       })
     }
    const onChange = (page) => {
        setReqData(prev => ({ ...prev, page }))
    }
    //  当用户点击页码发生变化时
    const onShowSizeChange = (_, size) => {       
        setReqData(prev => ({ ...prev, page: 1, per_page: size }))
    }
    // 删除功能
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [ deleteId, setDeleteId ] = useState() //将点击删除时的id存入进来
    const handelDelete = (id) => {
        setDeleteId(id)
        setIsModalOpen(true);
    }
    // 点击确定进行删除操作
    const handleOk = async() => {
        await deleteArticleAPI(deleteId)
        setIsModalOpen(false);
        message.success('删除数据成功')
        reqData.page = 1
        setReqData({ ...reqData })
    }
    // 点击取消
    const handleCancel = () => {
        setIsModalOpen(false);
    }
    // 点击编辑
    const onExit = (id) => {
      navigate(`/publish?id=${id}`)
    }
    const columns = [
            {   
                align: "center",
                title: '封面',
                dataIndex: 'cover',
                render: (cover) => cover.images.length !==0 ? 
                 <img style={{width: 60, height: 40}} src={cover.images[0]} alt="null"></img> :
                  '无封面'
            },
            {
                title: '标题',
                align: "center",
                dataIndex: 'title',
            },
            { 
                title: '状态',
                align: "center",
                dataIndex: 'status',
                render:(status) => status === 1 ? <Tag color="warning">待审核</Tag> : <Tag color="success">审核通过</Tag>
            },
            {
                title: '发布时间',
                width: 200,
                dataIndex: 'pubdate',
                align: "center",
            },
            {
                title: '阅读数',
                dataIndex: 'read_count',
                align: "center",
            },
            {
                title: '评论数',
                dataIndex: 'comment_count',
                align: "center",
            },
            {
                title: '点赞数',
                align: "center",
                dataIndex: 'like_count',
            },
            {
                title: '操作',
                align: "center",
                dataIndex: 'operate',
                render: (_,row) => (
                    <Space size="middle">
                        {/* 编辑按钮 */}
                        <Button 
                          onClick={() => onExit(row.id)}
                          type="primary" 
                          shape="circle"  
                          icon={<FormOutlined />}>
                        </Button>
                        {/* 删除按钮 */}
                        <Button 
                          type="primary" 
                          danger 
                          shape="circle"  
                          icon={<RestOutlined />}
                          onClick={() => handelDelete(row.id) }>
                        </Button>
                    </Space>
                ),
            },
    ];

    return (
        <div className="article">
            <Card className="artCardHearder">
               <div className="artBreadcrumb">
                 <Breadcrumb items={[ { title: <Link to="/">首页</Link>},{ title: '文章列表'}]}/>
                </div>
               <Form className="artHeaderForm" onFinish={onFinish}>
                  <Form.Item label="状态" name={'status'}>
                      <Radio.Group>
                          <Radio value={''}>全部</Radio>
                          <Radio value={1}>待审核</Radio>
                          <Radio value={2}>审核通过</Radio>
                        </Radio.Group>
                  </Form.Item>
                  <Form.Item label="频道" name={'channel_id'}>
                      <Select  placeholder="请选择频道">
                        {channelList.map(item =><Option value={item.id} key={item.id}> {item.name} </Option>)}
                      </Select>
                  </Form.Item>
                  <Form.Item label="日期" name={'date'}>
                      <RangePicker  />
                  </Form.Item>
                  <Form.Item>
                        <Button type="primary" htmlType="submit">点击筛选</Button>
                    </Form.Item>
               </Form>
               <Table scroll={{y: 430}} loading={loading} rowKey="id" dataSource={articleList} columns={columns}  pagination={false}/>
               <Pagination 
                    total={totalCount} //总数
                    pageSize={reqData.per_page} //每页的条数     
                    current={reqData.page}
                    align="end"
                    onChange={onChange}
                    onShowSizeChange={onShowSizeChange}
                    pageSizeOptions={[5,10,20,50]}
                 />
            </Card>
              <Modal
                title="删除操作"
                width={400}
                open={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel} >
                <p>确定要删除这条数据吗??</p>
            </Modal>
        </div>
    )
}
export default Article